<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="选择商城">
                <a-select
                  allowClear
                  v-model="queryParam.cash_store_id"
                  :filter-option="filterOption"
                  show-search
                  @change="handleSearch"
                >
                  <a-select-option :value="item.id" v-for="item in storeList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="起止时间">
                <a-range-picker
                  format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  @change="onChange"
                  @calendarChange="calendarChange"
                  :ranges="ranges"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="提现方式">
                <a-select allowClear v-model="queryParam.type">
                  <a-select-option value="0">微信支付</a-select-option>
                  <a-select-option value="1">支付宝</a-select-option>
                  <a-select-option value="2">银行卡</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button @click="$refs.table.refresh(true)" type="primary">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="$refs.table.refresh(1)">
          <a-radio-button :value="item.value" v-for="(item, index) in options" :key="index">
            {{ item.title }}
          </a-radio-button>
        </a-radio-group>
      </div>
      <s-table
        row-key="id"
        size="default"
        :columns="columns"
        :scroll="{ x: 'max-content' }"
        :data="loadData"
        ref="table"
      >
        <span slot="baseinfo" slot-scope="text, record">
          <div class="imgTxt">
            <a-avatar shape="square" :src="record.store_logo" :size="48" />
            <div class="txt">
              {{ record.store_name }}
            </div>
          </div>
        </span>
        <span slot="type" slot-scope="text">
          {{ String(text) ? TYPE[text] : '' }}
        </span>
        <span slot="accountinfo" slot-scope="text, record">
          <template v-if="parseInt(record.type) == 0">
            <a-popover title="微信转账">
              <template slot="content">
                <div class="style-font">姓名：{{ record.name }}</div>
                <span class="style-font">微信号：{{ record.mobile }}</span>
                <div class="style-font">提现到微信</div>
              </template>
              <span>微信转账</span>
            </a-popover>
          </template>
          <template v-if="parseInt(record.type) == 1">
            <a-popover title="支付宝">
              <template slot="content">
                <div class="style-font">姓名：{{ record.name }}</div>
                <span class="style-font">微信号：{{ record.mobile }}</span>
                <div class="style-font">提现到支付宝</div>
              </template>
            </a-popover>
            <span>支付宝</span>
          </template>
          <template v-if="parseInt(record.type) == 2">
            <a-popover title="银行转账">
              <template slot="content">
                <div class="style-font">姓名：{{ record.name }}</div>
                <div class="style-font">开户行：{{ record.bank_name }}</div>
                <span class="style-font">微信号：{{ record.mobile }}</span>
                <div class="style-font">提现到银行</div>
              </template>
            </a-popover>
            <span>银行转账</span>
          </template>
          <template v-if="parseInt(record.type) == 3">
            <div class="style-font">余额提现</div>
          </template>
        </span>
        <span slot="price" slot-scope="price">
          <div class="style-font">{{ price }}</div>
        </span>
        <span slot="time" slot-scope="text, record">
          {{ record.created_at > 0 ? $moment(record.created_at * 1000).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </span>
        <span slot="status" slot-scope="text, record">
          <template v-if="record.pay_type != 1">
            {{ statusFilter(record.status) }}
            <template v-if="record.status == 2">({{ typeFilter(record.type) }})</template>
            <template v-if="record.status == 5">
              <span>已打款</span>
            </template>
          </template>
          <template v-else>
            {{ statusFilter(record.status) }}<template v-if="record.status == 2">(微信自动打款)</template>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handle('remove', record)">删除</a-button>

          <a-button v-if="parseInt(record.status) === 0" type="link" @click="handleStatus(record, 1)">同意</a-button>
          <a-button v-if="parseInt(record.status) === 0" type="link" @click="openForm(record, 3)">拒绝</a-button>
          <a-button v-if="parseInt(record.status) === 1" type="link" @click="handle('withdraw', record)">打款</a-button>

          <!-- <template v-if="parseInt(record.status) === 0 || parseInt(record.status) === 1">
            <a-divider type="vertical" />
            <a-dropdown>
              <a-menu slot="overlay">
                <a-menu-item v-if="parseInt(record.status) === 0">
                  <a @click="handleStatus(record, 1)">同意</a>
                </a-menu-item>
                <a-menu-item v-if="parseInt(record.status) === 0">
                  <a @click="openForm(record, 3)">拒绝</a>
                </a-menu-item>
                <a-menu-item v-if="parseInt(record.status) === 1">
                  <a @click="handle('withdraw', record)">打款</a>
                </a-menu-item>
              </a-menu>
              <a class="ant-dropdown-link"> 更多 <a-icon type="down" /> </a>
            </a-dropdown>
          </template> -->
        </span>
      </s-table>
    </a-card>

    <a-modal width="700px" v-model="visible" title="拒绝原因" ok-text="确认" cancel-text="取消" @ok="onSubmit">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="拒绝原因" prop="reject_reason">
          <a-input v-model="form.reject_reason" allowClear />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
import moment from 'moment'
import { STable } from '@/components'
import { cashList, cashApply, cashConfirm, cashDel } from '@/api/singleFinance'
import { wechatMpCardList } from '@/api/wechartVipCard'

const STATUS = {
  0: '审核中',
  1: '待打款',
  2: '已完成',
  3: '已拒绝',
}

const TYPE = {
  0: '微信转账',
  1: '支付宝转账',
  2: '银行卡转账',
  3: '余额转账',
}
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '店铺信息',
    dataIndex: 'baseinfo',
    width: 200,
    scopedSlots: { customRender: 'baseinfo' },
  },
  {
    title: '提现方式',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' },
  },
  {
    title: '提现账号',
    width: 220,
    scopedSlots: { customRender: 'accountinfo' },
  },
  {
    title: '提现金额',
    dataIndex: 'price',
    scopedSlots: { customRender: 'price' },
  },
  {
    title: '申请时间',
    dataIndex: 'created_at',
    scopedSlots: { customRender: 'time' },
    width: 150,
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    width: '170px',
  },
]

export default {
  name: 'ShareCash',
  components: {
    STable,
  },
  data() {
    return {
      TYPE,
      storeList: [],
      options: [
        {
          title: '全部',
          value: -1,
        },
        {
          title: '待审核',
          value: 0,
        },
        {
          title: '已同意',
          value: 1,
        },
        {
          title: '已拒绝',
          value: 3,
        },
      ],
      tabKey: '',
      selectDate: null,
      locale: zhCN,
      ranges: {
        一月内: () => [moment().startOf('day').subtract(1, 'month'), moment()],
        昨天: () => [moment().startOf('day').subtract(1, 'days'), moment().endOf('day').subtract(1, 'days')],
        最近一周: () => [moment().startOf('day').subtract(1, 'weeks'), moment()],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      form: this.$form.createForm(this),
      // 表头
      columns,
      // 权限树
      modalLoading: false,
      defaultCheckedKeys: [],
      // 查询条件参数
      queryParam: {
        start_time: null,
        end_time: null,
        status: -1,
        type: '',
        cash_store_id: '',
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let queryParam = JSON.parse(JSON.stringify(this.queryParam))
        if (queryParam.type === '') {
          queryParam.type = '-1'
        }
        Object.assign(parameter, queryParam)
        return cashList(parameter).then((res) => {
          return res.data
        })
      },

      visible: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      form: {
        reject_reason: '',
      },
      rules: {
        reject_reason: [{ required: true, message: '拒绝理由不能为空', trigger: 'blur' }],
      },
    }
  },
  async created() {
    const hide = this.$message.loading('加载中', 0)
    const res = await wechatMpCardList()
    if (res.code == 0) {
      this.storeList = res.store_list || []
    }
    hide()
  },

  computed: {
    getStoreName() {
      return (id) => {
        let { storeList } = this
        if (!storeList.length) return ''

        let item = storeList.find((el) => el.id === id)
        return item ? item.name : ''
      }
    },
  },
  watch: {
    visible(e) {
      if (!e) this.resetForm()
    },
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    handleSearch(value) {
      let [item] = this.storeList.filter((d, index) => {
        return d.id == value
      })
      this.queryParam.cash_store_id = item.id
    },

    resetSearchForm() {
      this.queryParam = {
        start_time: moment(new Date()),
        end_time: moment(new Date()),
      }
    },
    moment,
    // 选中日期事件
    calendarChange(date, dateString) {
      // if (date.length <= 1) {
      //   // 选中开始日期事件，设置结束日期必须大于1天
      //   this.selectDate = date[0].add(1, 'days')
      // } else {
      //   this.selectDate = null
      // }
      this.selectDate = date[0]
    },
    // 选择后的事件
    onChange(date, dateString) {
      this.queryParam.start_time = dateString[0]
      this.queryParam.end_time = dateString[1]
    },
    statusFilter(key) {
      return STATUS[key]
    },
    typeFilter(key) {
      return TYPE[key]
    },

    openForm(record) {
      this.visible = true
      this.form = {
        name: '',
        id: record.id,
        status: 3,
      }
    },
    async handleStatus(record, status) {
      var params = {
        id: [record.id],
        status: status,
        store_id: -1,
        reject_reason: record.reject_reason ? record.reject_reason : '',
      }
      var returnMsg = '拒绝成功！'
      if (status === 1) {
        returnMsg = '通过成功！'
      }
      const hide = this.$message.loading('加载中', 0)
      const res = await cashApply(params)
      hide()

      if (!res.code) {
        this.$refs.table.refresh(true)
        this.visible = false
        this.$message.success(returnMsg)
        if (this.$refs.resetFields) {
          this.$refs.ruleForm.resetFields()
        }
        return
      }
      this.$message.error(returnMsg)
    },
    handleConfirm(record, status) {
      var params = {
        id: record.id,
        status: status,
      }
      applyConfirm(params).then((res) => {
        this.modalLoading = false
        if (res.code !== 0) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$refs.table.refresh()
          this.$message.success('处理成功')
        }
      })
    },

    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { form } = this
          this.handleStatus(form, 3)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },

    async handle(type, el) {
      const hide = this.$message.loading('加载中', 0)
      let res

      switch (type) {
        case 'withdraw':
          this.$confirm({
            title: '提示?',
            content: '是否打款',
            onOk: async () => {
              res = await cashConfirm({
                id: el.id,
              })
              hide()

              if (!res.code) {
                this.$refs.table.refresh()
                this.$message.success('操作成功~')
              } else {
                this.$error({
                  content: res.msg,
                })
              }
            },
            onCancel: () => {
              hide()
            },
          })

          break

        case 'remove':
          res = await cashDel({
            id: [el.id],
          })

          break
      }

      hide()
      if (res) {
        if (!res.code) {
          this.$refs.table.refresh()
          this.$message.success('操作成功~')
        } else {
          this.$error({
            content: res.msg,
          })
        }
      }
    },
  },
}
</script>

<style lang="less" scoped>
.top_card {
  /deep/.ant-card-body {
    padding-bottom: 0;
  }
  /deep/.ant-tabs-bar {
    margin-bottom: 0;
    border-bottom: 1px solid #fff;
  }
}
.style-font {
  font-size: 14px;
  font-weight: 500;
}

.button_style {
  margin-top: 3px;
}

.imgTxt {
  display: flex;
  align-items: center;

  .txt {
    margin-left: 10px;
    overflow: hidden;
    flex: 1;
  }
}
</style>
